package com.alks.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
public class IpAddressUtils {

    /**
     * 检测IP是否为内网IP（Y则为内网IP，N则为外网IP）
     * @param ipAddress
     * @return
     */
    private String ipAddressCheck(String ipAddress){
        InetAddress ia = null;
        try {
            InetAddress ad = InetAddress.getByName(ipAddress);
            byte[] ip = ad.getAddress();
            ia = InetAddress.getByAddress(ip);
        }  catch (UnknownHostException e) {
            String callerMethodName = Thread.currentThread().getStackTrace()[2].getMethodName(); // 直接获取调用者方法名
            log.warn("异常接口：{}\n异常原因：IP地址解析失败", callerMethodName, e);
        }
        if (ia != null&&(ia.isSiteLocalAddress() || ia.isLoopbackAddress())) {
            return "N";
        }
        return "Y";
    }

    /**
     * 获取客户端IP
     * @param request
     * @return
     */
    public static String getClientIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            // 如果是localhost访问，可能会返回"0:0:0:0:0:0:0:1"或"127.0.0.1"，这里简化处理
            if ("0:0:0:0:0:0:0:1".equals(ipAddress) || "127.0.0.1".equals(ipAddress)) {
                ipAddress = "127.0.0.1";
            }
        }

        // 多个代理的情况，第一个IP为客户端真实IP，多个IP按照','分割
        if (ipAddress != null && ipAddress.contains(",")) {
            ipAddress = ipAddress.split(",")[0];
        }

        return ipAddress;
    }
}
